package com.ktjy.ktmall.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktjy.common.annotation.Log;
import com.ktjy.common.core.controller.BaseController;
import com.ktjy.common.core.domain.AjaxResult;
import com.ktjy.common.core.page.TableDataInfo;
import com.ktjy.common.enums.BusinessType;
import com.ktjy.common.utils.poi.ExcelUtil;
import org.apache.poi.ss.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.ktjy.ktmall.domain.Attr;
import com.ktjy.ktmall.service.IAttrService;

import org.springframework.web.multipart.MultipartFile;

/**
 * 规格属性Controller
 *
 * @author ktjy
 * @date 2025-03-13
 */
@RestController
@RequestMapping("/ktmall/attr")
public class AttrController extends BaseController
{
    @Autowired
    private IAttrService attrService;


    @Log(title = "规格属性", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ktmall:attr:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<Attr> util = new ExcelUtil<Attr>(Attr.class);
        List<Attr> attrList = util.importExcel(file.getInputStream());
        String message = attrService.importAttr(attrList, updateSupport);
        return success(message);
    }


/**
 * 查询规格属性列表
 */
@PreAuthorize("@ss.hasPermi('ktmall:attr:list')")
@GetMapping("/list")
    public TableDataInfo list(Attr attr)
    {
        startPage();
        List<Attr> list = attrService.selectAttrList(attr);
        return getDataTable(list);
    }


    /**
     * 导出规格属性列表
     */
    @PreAuthorize("@ss.hasPermi('ktmall:attr:export')")
    @Log(title = "规格属性", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Attr attr) throws IOException {
        QueryWrapper<Attr> queryWrapper = new QueryWrapper<>();
        if (attr.getName() !=null){
            queryWrapper.like("name",attr.getName());
        }

        List<Attr> list = attrService.list(queryWrapper);

        // 添加序号列
        List<Map<String, Object>> exportList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Attr attr1 = list.get(i);
            Map<String, Object> exportData = new LinkedHashMap<>();
            exportData.put("index", i + 1); // 序号列的值自增，从1开始
            exportData.put("name", attr1.getName());
            exportData.put("order_num", attr1.getOrderNum());
            exportData.put("enabled", attr1.getEnabled()==0 ? "正常":"禁用");
            exportData.put("remark", attr1.getRemark());

            // 把exportData这个键值对集合添加到上面定义的exportList集合中
            // 注意看上面定义时是（List<Map<String, Object>>）
            exportList.add(exportData);
        }
        // 在内存操作，写出到浏览器
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
        writer.setOnlyAlias(true); // 设置成只导出有别名的字段
        // 自定义标题别名
        writer.addHeaderAlias("index", "编号");
        writer.addHeaderAlias("name", "属性名称");
        writer.addHeaderAlias("order_num", "排序值");
        writer.addHeaderAlias("enabled", "状态");
        writer.addHeaderAlias("remark", "备注");
        // 合并单元格
        writer.merge(4, "规格属性数据");
        // 自定义样式（背景色为绿色，字体为黑色）
        CellStyle greenStyle = writer.getWorkbook().createCellStyle();
        greenStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        greenStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        greenStyle.setAlignment(HorizontalAlignment.CENTER); // 添加居中对齐
        Font font = writer.getWorkbook().createFont();
        font.setColor(IndexedColors.BLACK.getIndex());
        greenStyle.setFont(font);
        // 设置第一行的样式，包括合并的单元格
        writer.setStyle(greenStyle, 0, 0);
        // 一次性写出列表内的对象到Excel，使用默认样式，强制输出标题，并排除不需要导出的列
        writer.write(exportList, true);

        // 设置浏览器响应的格式
        String fileName = URLEncoder.encode("规格属性数据", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * 获取规格属性详细信息
     */
    @PreAuthorize("@ss.hasPermi('ktmall:attr:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(attrService.getById(id));
    }

    /**
     * 新增规格属性
     */
    @PreAuthorize("@ss.hasPermi('ktmall:attr:add')")
    @Log(title = "规格属性", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Attr attr)
    {
        return toAjax(attrService.save(attr));
    }

    /**
     * 修改规格属性
     */
    @PreAuthorize("@ss.hasPermi('ktmall:attr:edit')")
    @Log(title = "规格属性", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Attr attr)
    {
        return toAjax(attrService.updateById(attr));
    }

    /**
     * 删除规格属性
     */
    @PreAuthorize("@ss.hasPermi('ktmall:attr:remove')")
    @Log(title = "规格属性", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Integer> ids)
    {
        return toAjax(attrService.removeByIds(ids));
    }
}